<?php
namespace app\index\controller;

use think\App;
use app\index\controller\IndexBaseController;
use think\facade\View;
use app\common\model\JfArticle as JfArticleModel;
use app\common\lib\Show;
use app\common\lib\Str;
use app\index\validate\Editor as EditorValidate;
use think\exception\ValidateException;
use think\Exception;

class Editor extends IndexBaseController {

  protected $jf_article_model;
  public function __construct(App $app)
  {
      parent::__construct($app);
      $this->jf_article_model = new JfArticleModel();
  }

  public function index()
  {
    return View::fetch('index');
  }
  /**
   * 创建新的文章
   */
  public function create()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求');
    }
    $qurey_info = $this->request->param();
    try {
      validate(EditorValidate::class)->scene('create')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    try {
      $content = $this->jf_article_model->content()->save(['content' => $qurey_info['content']]);
      $url = Str::getUrl();
      $data = [
        'user_id' => $this->jf_user_info->id,
        'title' => $qurey_info['title'],
        'summary' => $qurey_info['summary'],
        'cover_image' => $qurey_info['coverImage'],
        'url' => '/index/article/detile/'.$url.'.html',
        'content_id' => $content->id,
        'status' => 0
      ];
      $id = $this->jf_article_model->saveJfArticle($data);
      return Show::success([ 'article_id' => $id, 'content_id' => $content->id]);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * 更新文章
   */
  public function update()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求');
    }
    $qurey_info = $this->request->param();
    try {
      validate(EditorValidate::class)->scene('create')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    try {
      $this->jf_article_model->content()
        ->where(['id' => $qurey_info['contentId']])
        ->update(['content' => $qurey_info['content']]);
      $data = [
        'id' => $qurey_info['articleId'],
        'title' => $qurey_info['title'],
        'summary' => $qurey_info['summary'],
        'cover_image' => $qurey_info['coverImage'],
        'status' => $qurey_info['status']
      ];
      $result= $this->jf_article_model->updateJfArticle($data);
      return Show::success($result);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
}
